import Taro from "@tarojs/taro"
import { IUploadFileOptions, requestIsFullfilled, uploadFile } from "@/utils/request"

interface FileUploadResult {
  fullName: string
  isVideo: boolean
  name: string
  videoCoverImg?: INullable<string>
  videoDuration?: INullable<number>
}

export function fileUpload(filePath: string, options?: IUploadFileOptions) {
  return new Promise<FileUploadResult>(async (resolve, reject) => {
    try {
      const res = await uploadFile("/upload", filePath, options)
      if (res.statusCode === 200 && res.data) {
        res.data = JSON.parse(res.data)
        // @ts-ignore
        if (!requestIsFullfilled(res)) {
          // @ts-ignore
          throw new Error(res.data.message)
        }
        Taro.showToast({
          title: '头像上传成功',
          icon: 'success'
        })
        // @ts-ignore
        resolve(res.data.data)
      } else {
        throw new Error(res.errMsg)
      }
    } catch (error) {
      Taro.showToast({
        title: error?.message ?? '头像上传失败',
        icon: 'error'
      })
      reject(error)
    }
  })
}
